package org.blitengine.objects
{
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class ClipBlit extends BlitObject
	{
		private var bmp:BitmapData;		
		private var nframes:int;
		private var width:int, height:int;
		private var origin:Point;
		
		public function ClipBlit( clip:MovieClip, width:int, height:int, origin:Point = null )
		{
			super();
			bmp = createBitmap( clip, width, height, origin );
			this.width = width;
			this.height = height;
			this.origin = origin;
		}
		
		protected function createBitmap(clip:MovieClip, width:int, height:int, origin:Point = null):BitmapData
		{
			if(!origin)
				origin = new Point( 0, 0 );
			nframes = clip.currentScene.numFrames;
			var bmp:BitmapData = new BitmapData( width*nframes, height, true, 0x0 );
			var matrix:Matrix = new Matrix();
			matrix.translate( origin.x, origin.y );
			
			var i:int = 0;
			while(i<nframes)
			{
				bmp.draw( clip, matrix );
				matrix.translate( width, 0 );
				clip.nextFrame();
				i++;
			}
			
			return bmp;
		}
		
		private var frame:int = 0;
		
		override public function blit(bitmap:BitmapData, point:Point):void
		{
			
			frame = (frame+1)%nframes;
			bitmap.copyPixels(bmp, new Rectangle(frame*width, 0, 32, 32), new Point(point.x-origin.x, point.y-origin.y));
		}
	}
}